<template>
  <div class="kline-container">
    <div
      ref="klineChart"
      class="kline-chart"
      @wheel.prevent="handleWheel"
    ></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
// import { throttle } from "lodash";

export default {
  name: "KlineChart",
  data() {
    return {
      chartInstance: null,
      data: [], // K线数据
      maxDataLength: 100, // 最大数据长度
      currentDataIndex: 0, // 当前数据索引
    };
  },
  mounted() {
    this.initChart();
    this.fetchData();
  },
  methods: {
    initChart() {
      this.chartInstance = echarts.init(this.$refs.klineChart);
      const options = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
        },
        xAxis: {
          type: "category",
          data: [],
        },
        yAxis: {
          scale: true,
        },
        series: [
          {
            name: "K线",
            type: "candlestick",
            data: [],
          },
        ],
      };
      this.chartInstance.setOption(options);
    },
    fetchData() {
      // 模拟获取数据
      const newData = this.generateRandomData();
      this.data = [...this.data, ...newData];
      this.updateChart();
    },
    generateRandomData() {
      // 生成随机 K 线数据
      const data = [];
      for (let i = 0; i < 10; i++) {
        const open = Math.random() * 100;
        const close = open + Math.random() * 10 - 5;
        const low = Math.min(open, close) - Math.random() * 5;
        const high = Math.max(open, close) + Math.random() * 5;
        data.push([open, close, low, high]);
      }
      return data;
    },
    updateChart() {
      const options = this.chartInstance.getOption();
      options.series[0].data = this.data.slice(
        this.currentDataIndex,
        this.currentDataIndex + this.maxDataLength
      );
      options.xAxis.data = this.data.map((_, index) => `Index ${index}`);
      this.chartInstance.setOption(options);
    },
    handleWheel(event) {
      const delta = event.deltaY;
      if (delta > 0) {
        // 向下滑动，加载更多历史数据
        this.currentDataIndex -= 10;
        if (this.currentDataIndex < 0) {
          this.currentDataIndex = 0;
        }
        this.updateChart();
      } else {
        // 向上滑动，加载更多未来数据
        this.currentDataIndex += 10;
        if (this.currentDataIndex > this.data.length - this.maxDataLength) {
          this.currentDataIndex = this.data.length - this.maxDataLength;
        }
        this.updateChart();
      }
    },
  },
};
</script>

<style scoped>
.kline-container {
  width: 100%;
  height: 600px;
}
.kline-chart {
  width: 100%;
  height: 100%;
}
</style>